<?php
namespace app\index\controller\xiaoshuo;

use app\BaseController;
use app\index\model\XiaoshuoBase;
use think\facade\View;
use app\index\model\XiaoshuoList;
use app\index\model\XiaoshuoArchives;

class index extends BaseController
{
    public function index()
    {
      //     $url='http://www.mhtwx.la/mulu/1-1.html';
					 // $this->getXiao($url);
                     
							View::assign('count',XiaoshuoList::where('status',NULL)->count());
         return View::fetch();
    }
		
		public function show(){
			
			return View::fetch();
		}
		
		public function getBase(){
			$start=\input('param.start');
			$list=XiaoshuoList::where('status',NULL)->limit($start,1)->order('id asc')->select();
			if(!$list->isEmpty()){
				// file_put_contents('./1.txt',$start);
			return \reMsg('1',$list,'书源',++$start);
			}else{
				return \reMsg('-1','','没有书了');
			}
		}
    //写入章节
    public function writeArchives()
    {
			
			  	$start=\input('param.start');
			  $model=new XiaoshuoArchives();
			  $res=$model->limit($start,1)->order('id desc')->select()->toArray();
				if(empty($res)){
					return reMsg('-2','','没有了','结束');
				}
			  $res=$res[0];
				if($res['status']=='1'){
					return reMsg('-1','','已采集'.$res['chaptername'],++$start);
				}
        $file=$this->httpRequest($res['arcurl']);
        $data=[];
        $per='/<div class=\"content\".*><div class=\"con_r\">.*<\/div><p class=\"contnew\">.*<\/p>([\s\S]*)<div class=\"con_l\">/iU';
        preg_match_all($per, $file, $arr);
				$content=preg_replace('/wwW.mhtwx.la|www.mhtwx.la|WWW.mhtwx.la|mhtwx.la/','好看的小说',$arr[1][0]);
				$content=preg_replace('/无弹窗广告|棉花糖小说网/','好看的小说',$content);
         $data['content']=$content;
				 $data['status']=1;
				$res2=$model->where('id',$res['id'])->save($data);
				if($res2){
					  return reMsg('1','','采集完成'.$res['chaptername'],++$start);
				}else{
					return \reMsg('-1','','已完成');
				}
    }
    //写入书
    public function writeBooks()
    {
			//set_time_limit(0);
		    	$url=input('param.url');
          $id=input('param.id');
     
        $file=$this->httpRequest($url);
	 
				$per='/<div class=\"novel_list\" .*>([\s\S]*)<\/div>/iU';
				preg_match_all($per,$file,$arr);
		
        $per='/<dd><a href=\"(.*)\">([\s\S]*)<\/a><\/dd>/iU';
			
				preg_match_all($per,$arr[1][0],$arr);
				$model=new XiaoshuoArchives();
				$data=[];
	
				 foreach($arr[1] as $key=>$v){
					 $res=$model->where([
						 'chaptername'=>$arr[2][$key],
						 'fid'=>$id
					 ])->findOrEmpty();
					 if($res->isEmpty()){
					 $data[$key]['chaptername']=$arr[2][$key];
					 $data[$key]['arcurl']=$url.$v;
					 $data[$key]['fid']=$id;
					 $data[$key]['updatetime']=time();
					 }
				 }
			
				// $limit=100;
				// $count=ceil(count($data)/$limit);

				// for ($i=1;$i<=$count;$i++){
				//     $offset=($i-1)*($limit);
				//     $ids=array_slice($data,$offset,$limit);
				//      $res= $model->saveAll($ids);
				
				// }
           $res= $model->saveAll($data);  
				 if ($res) {
					 XiaoshuoList::update(['id' => $id, 'status' => '1']);
				    return reMsg('1',$data,'完成');
				 }
    }
    //设置列表页面地址
    public function setlist()
    {
        if (request()->isAjax()) {
            $url=input('param.url');
						$k=input('param.k');
            return $this->getXiao($url,$k);
        }
    }
    //获取棉花糖小说列表
    public function getXiao($url,$k)
    {

        $file=$this->httpRequest($url,true);
			//dump(\file_get_contents("compress.zlib://".$url));
        //$per='/<div class=\"info\">.*<div class=\"title\">.*<a href=\"(.*)\" .*>《(.*)》<\/a>.*<a.*>(.*)<\/a>.*<\/div>.*<div class=\"intro\">(.*)<\/div>.*<\/div>/iU';
				$per='/<div class=\"title\"><h2><a href=\"(.*)\" .*>《(.*)》<\/a><\/h2>.*<a.*>(.*)<\/a>.*<\/div><div class=\"intro\">([\s\S]*)<\/div>/iU';
 
        preg_match_all($per, $file, $arr);
		 
        $file=@$arr[0][0];
				if(empty($file)){
					return reMsg('-1','','没有了');
				}
       $category=['无分类','玄幻魔法','武侠修真','都市言情','历史军事','侦探推理','网游动漫','科幻小说','恐怖灵异','同人小说','穿越小说'];
        $data=[];
        $time=time();
        foreach ($arr[1] as $key=>$v) {
            $data[$key]['url']=$v;
						
            $data[$key]['book_name']=$arr[2][$key];
            $data[$key]['update_time']=$time;
            $data[$key]['author']=$arr[3][$key];
            $data[$key]['description']=msubstr(trim($arr[4][$key]),0,230);
						
						$data[$key]['category']=$category[$k];
        }
      $res= $this->writeBase($data);
		    
        if ($res) {
           return reMsg('1','','完成');
        }
    }

    //写入源地址进数据库
    public function writeBase($data)
    {
	
        $model=new XiaoshuoList();
        $i=0;
        foreach ($data as $key=>$v) {
            $where=[
                     'book_name'=>$v['book_name'],
                     'url'=>$v['url']
                 ];
            $res=$model->where($where)->findOrEmpty();
                 
            if (!$res->isEmpty()) {
                unset($data[$key]);
            }
        }
			
        $res= $model->saveAll($data);
        if ($res) {
              return 1;
        }else{
					return -1;
				}
    }


    public function httpRequest($sUrl,$gzip='false',$aHeader='', $aData='')
    {
        $ch = curl_init();
        if (substr($sUrl, 0, 5)=='https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        }
        if (empty($aHeader)) {
            $aHeader = [
                             "Content-type:application/json;charset=utf-8",
                             "Accept:application/json",
                             ];
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $sUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        curl_setopt($ch, CURLOPT_POST, 0);
        if (!empty($aData)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($aData)); //格式
        }
			 if($gzip) curl_setopt($ch, CURLOPT_ENCODING, "gzip"); 
        $sResult = curl_exec($ch);
        if ($sError=curl_error($ch)) {
            die($sError);
        }
        curl_close($ch);
        return $sResult;
    }
}
